<template>
	<div class="import-confirmation">
		<!-- <div class="confirmation-header">
			<h3>导入确认</h3>
			<div class="confirmation-info">
				<el-tag type="info">有效数据行数: {{ validDataCount }}</el-tag>
			</div>
		</div> -->

		<div class="confirmation-details">
			<el-descriptions title="导入信息" :column="2" border>
				<el-descriptions-item label="有效数据行数">{{ validDataCount }}</el-descriptions-item>
				<el-descriptions-item label="学年">{{ academicYearInfo }}</el-descriptions-item>
				<el-descriptions-item label="班级">{{ classInfo }}</el-descriptions-item>
				<el-descriptions-item label="成绩类型">{{ examTypeInfo }}</el-descriptions-item>
				<el-descriptions-item label="科目" :span="2">
					<el-tag
						v-for="(subject, index) in subjectList"
						:key="index"
						class="subject-tag"
						type="success"
					>
						{{ subject }}
					</el-tag>
				</el-descriptions-item>
			</el-descriptions>
		</div>

		<div class="confirmation-warning">
			<el-alert
				title="确认导入将直接影响数据库中的数据，请确认数据无误后再操作。"
				type="warning"
				:closable="false"
				show-icon
			/>
		</div>

		<div class="action-buttons">
			<el-button @click="goBack">返回上一步</el-button>
			<el-button type="primary" @click="confirmImport" :loading="importing"> 确认导入 </el-button>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, computed, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { uploadFileService } from '../../../api/file'
import { addScoreListService } from '@/api/education/score'

interface ImportOptions {
	dataCount?: number
	subjectId?: string
	classId?: string
	examType?: string
	academicYear?: string
	className?: string
	subjectList?: string[]
}

interface scoreListWithOptions {
	data: any[]
	options: ImportOptions
}

const props = defineProps<{
	excelData: scoreListWithOptions | any[]
}>()
console.log(props)

const emit = defineEmits(['import-success', 'import-failed', 'go-back'])

// 导入状态
const importing = ref(false)

// 从上一步接收的导入选项
const options = computed<ImportOptions>(() => {
	// 从处理后的数据中提取导入选项
	if (props.excelData && 'options' in props.excelData) {
		return props.excelData.options
	}
	return {
		importType: '',
		subjectId: '',
		classId: '',
		examType: '',
		dataCount: 0
	}
})

// 实际数据
const scoreList = computed(() => {
	if (props.excelData && 'scoreData' in props.excelData) {
		return props.excelData.scoreData || []
	}
	return props.excelData || []
})

// 有效数据条数
const validDataCount = computed(() => {
	return options.value.dataCount || 0
})

// 科目列表
const subjectList = computed(() => {
	return options.value.subjectList || []
})

// 学年信息
const academicYearInfo = computed(() => {
	return options.value.academicYear || '未指定'
})

// 班级信息
const classInfo = computed(() => {
	return options.value.className || '未指定'
})

// 考试类型信息
const examTypeInfo = computed(() => {
	const examType = options.value.examType || ''
	const examTypeMap: Record<string, string> = {
		midterm: '期中成绩',
		final: '期末成绩',
		usual: '平时成绩',
		total: '总评成绩'
	}
	return examTypeMap[examType] || examType || '未指定'
})

// 返回上一步
const goBack = () => {
	emit('go-back')
}

// 确认导入
const confirmImport = async () => {
	try {
		// 弹出最终确认框
		await ElMessageBox.confirm(`确定要导入这些数据吗？此操作会覆盖已存在的数据。`, '导入确认', {
			confirmButtonText: '确认导入',
			cancelButtonText: '取消',
			type: 'warning'
		})

		importing.value = true

		// // 构建导入数据
		// const importData = {
		// 	data: scoreList.value,
		// 	options: options.value
		// }

		console.log(scoreList.value)

		// 处理数据，保留所有必要字段，即使值为null
		const cleanedScoreList = Array.isArray(scoreList.value)
			? scoreList.value.map((item: Record<string, any>) => {
					const cleanedItem = { ...item }
					// 确保 theoryTotal 和 practiceTotal 字段存在，即使值为null
					if (!cleanedItem.hasOwnProperty('theoryTotal')) {
						cleanedItem.theoryTotal = null
					}
					if (!cleanedItem.hasOwnProperty('practiceTotal')) {
						cleanedItem.practiceTotal = null
					}

					// 移除不重要的null值属性，但保留成绩相关字段
					const importantFields = [
						'theoryTotal',
						'practiceTotal',
						'midTermTheory',
						'finalTheory',
						'usualTheory',
						'midTermPractice',
						'finalPractice',
						'usualPractice',
						'aboutTheory',
						'aboutPractice'
					]

					for (const key in cleanedItem) {
						if (cleanedItem[key] === null && !importantFields.includes(key)) {
							delete cleanedItem[key]
						}
					}
					return cleanedItem
				})
			: []

		const res = await addScoreListService(cleanedScoreList)

		// 处理响应
		if (res.data && res.data.code === 1) {
			ElMessage.success('成绩导入成功')
			emit('import-success')
		} else {
			throw new Error(res.data?.msg || '导入失败')
		}
	} catch (error: any) {
		if (error === 'cancel') {
			// 用户取消操作
			return
		}

		console.error('导入失败:', error)
		const errorMessage = error.message || '导入过程中发生错误'
		emit('import-failed', errorMessage)
		ElMessage.error(errorMessage)
	} finally {
		importing.value = false
	}
}
</script>

<style lang="scss" scoped>
.import-confirmation {
	width: 100%;

	.confirmation-header {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		margin-bottom: 20px;

		h3 {
			margin: 0;
			color: var(--el-text-color-primary);
		}

		.confirmation-info {
			display: flex;
			gap: 10px;
		}
	}

	.confirmation-details {
		margin-bottom: 20px;
	}

	.import-options {
		margin-bottom: 20px;

		h4 {
			margin-top: 0;
			margin-bottom: 15px;
			color: var(--el-text-color-primary);
			font-weight: normal;
		}
	}

	.confirmation-warning {
		margin-bottom: 20px;
	}

	.action-buttons {
		display: flex;
		justify-content: center;
		gap: 15px;
	}

	.subject-tag {
		margin-right: 8px;
		margin-bottom: 5px;
	}
}
</style>
